from fastapi import APIRouter, BackgroundTasks
from app.services.backtest import run_backtest
from datetime import date
from pydantic import BaseModel, Field
from app.services.market_crawler import CH

router = APIRouter(prefix="/api/bt")

class BtBody(BaseModel):
    name: str
    codes: list[str] = Field(min_items=1)
    start: date
    end: date

@router.post("/run")
def bt_run(
    body: BtBody, 
    background: BackgroundTasks
    ):
    background.add_task(run_backtest, body.name, body.codes, body.start, body.end)
    return {"msg": "backtest started"}

@router.get("/result/{run_id}")
def bt_result(run_id: int):
    df = CH.query_dataframe('SELECT * FROM daily_pnl WHERE run_id = {} ORDER BY trade_date'.format(run_id))
    if df.empty:
        return {"status": "running"}
    stats = CH.query_dataframe('SELECT * FROM backtestrun WHERE id = %(id)s', {'id': run_id}).iloc[0]
    return {
        "status": "done",
        "nav": df['nav'].tolist(),
        "dates": df['date'].astype(str).tolist(),
        "stats": stats.to_dict()
    }
